<?php
/*! \brief
 * This is WFMutex class
 * This is the Class that manipulate Mutex process
 * Usage : after trigger widget update button, will use WFMutex to avoid multiple update widget process.
 * \author Andy Lou (William Su rewrap this class)
 */
class WFMutex {
	//const PID_NAME = "widgetpool.pid";
	protected $filename;
	protected $fp;
	protected $already_running = false;
	/**
	 * @var WF
	 */
	private $objFramework;
	public function __construct($objFramework,$strPathPidFile) {
	    $this->objFramework = $objFramework;
		////$this->filename = $this->getWFHome() . '/repository/' . self::PID_NAME;
		$this->filename = $strPathPidFile;
		mydebug_log( "pid file:" . $this->filename );
		$this->fp = fopen ( $this->filename, 'w+' );
		if (! flock ( $this->fp, LOCK_EX + LOCK_NB )) {
			mydebug_log( "FAILED lock {$this->filename}" );
			$this->already_running = true;
			fclose ( $this->fp );
		} else {
			mydebug_log( "Acquired lock {$this->filename}" );
		}
	}
	public function isRunning() {
		return $this->already_running;
	}
	public function __destruct() {
		if (! $this->already_running) {
			flock ( $this->fp, LOCK_UN );
			fclose ( $this->fp );
			unlink ( $this->filename );
			mydebug_log( "Releasing lock {$this->filename}" );
		}
	}
} 